package pilgun.eshop.repository;

import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;

import pilgun.eshop.domain.Item;








public class ItemRepositoryTemplate implements ItemRepository {
	
	private static final String ITEM_SEL_QUERY = "SELECT id, name, description, category, price, stock FROM Merchandise";
    private static final String INSERT_ITEM = "INSERT INTO Merchandise (id, name, description, category, price, stock) values (?, ?, ?, ?, ?, ?)";
    private final JdbcOperations template;
 
	
	@Autowired
	public ItemRepositoryTemplate(JdbcOperations template) {
	this.template = template;
	}
	
    public List<Item> getItemList(){
        return template.query(ITEM_SEL_QUERY,new RowMapper<Item>(){
        	@Override
        	public Item mapRow(ResultSet rs, int rowNum) throws SQLException {
                Item anItem = new Item();
                anItem.setId(rs.getInt("id"));
                anItem.setName(rs.getString("name"));
                anItem.setDescription(rs.getString("description"));
                anItem.setCategory(rs.getString("category"));
                anItem.setPrice(rs.getDouble("price"));
                anItem.setStock(rs.getInt("stock"));
                return anItem;
            }
        });
        
    }
    
    
    public void addToList(Item item){
    	template.update(
    	        INSERT_ITEM,
    	        item.getId(), 
    	        item.getName(),
    	        item.getDescription(),
    	        item.getCategory(),
    	        item.getPrice(),
    	        item.getStock());
    }
    
    public Item getItemById(int id){
        return template.queryForObject(ITEM_SEL_QUERY + " where id = ?",new RowMapper<Item>(){
        	@Override
            public Item mapRow(ResultSet rs, int rowNum) throws SQLException {
                Item anItem = new Item();
                anItem.setId(rs.getInt("id"));
                anItem.setName(rs.getString("name"));
                anItem.setDescription(rs.getString("description"));
                anItem.setCategory(rs.getString("category"));
                anItem.setPrice(rs.getDouble("price"));
                anItem.setStock(rs.getInt("stock"));
                return anItem;
            }
        },
        id);
        
    }
	
}
